const { ObjectId } = require("mongodb");

function addUser(user) {
  return new Promise((resolve, reject) => {
    const MongoClient = require("mongodb").MongoClient;
    const url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function (err, db) {
      if (err) {
        resolve({
          msg: "添加用户失败",
          err,
        });
      }
      const dbo = db.db("my_express_server");

      dbo.collection("user").insertOne(user, function (err, res) {
        db.close();
        if (err) {
          resolve({
            msg: "添加用户失败",
            err,
          });
        } else {
          resolve({
            msg: "添加用户成功",
            res,
          });
        }
      });
    });
  });
}

function deleteUser(id) {}

function updateUser(id, user) {}

/* 按照条件查询指定的用户 */
function getUsers(user) {
  return new Promise((resolve, reject) => {
    const MongoClient = require("mongodb").MongoClient;
    const url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function (err, conn) {
      if (err) {
        resolve([]);
        return;
      }

      const dbObj = conn.db("my_express_server");

      // 如果查询条件含有_id属性 修改user的_id属性修改为对象形式ObjectId(id)
      user._id && (user._id = new ObjectId(user._id))

      dbObj
        .collection("user")
        .find(user) //{username:"heige",password:"123456"}
        .toArray(function (err, dataArr) {
          conn.close();

          /* 查询成功 且 结果不为空数组 才算登录成功 */
          if (!err && dataArr.length) {
            resolve(dataArr);
          } else {
            resolve([]);
          }
        });
    });
  });
}

module.exports = {
  addUser,
  deleteUser,
  updateUser,
  getUsers,
};
